package com.jyniubi.gmail.item.service.impl;

import com.jyniubi.gmail.common.bean.ResponseVo;
import com.jyniubi.gmail.item.feign.GmallPmsClient;
import com.jyniubi.gmail.item.feign.GmallSmsClient;
import com.jyniubi.gmail.item.feign.GmallWmsClient;
import com.jyniubi.gmail.item.service.ItemService;
import com.jyniubi.gmail.item.vo.ItemVo;
import com.jyniubi.gmail.pms.entity.*;
import com.jyniubi.gmail.pms.vo.ItemGroupVo;
import com.jyniubi.gmail.pms.vo.SaleAttrValueVo;
import com.jyniubi.gmail.sms.vo.ItemSaleVo;
import com.jyniubi.gmail.wms.entity.WareSkuEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private GmallPmsClient pmsClient;
    @Autowired
    private GmallSmsClient smsClient;
    @Autowired
    private GmallWmsClient wmsClient;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private TemplateEngine templateEngine;

    public void generateHtml(ItemVo itemVo){
        try (PrintWriter printWriter = new PrintWriter("D:\\node\\framework\\电商\\html\\" + itemVo.getSkuId() + ".html");){
            Context context = new Context();
            context.setVariable("itemVo",itemVo);
            this.templateEngine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    public ItemVo loadData(Long skuId) {
        ItemVo itemVo = new ItemVo();
        //1.根据skuId查询sku	V
        CompletableFuture<SkuEntity> skuFuture = CompletableFuture.supplyAsync(() -> {
            ResponseVo<SkuEntity> skuEntityResponseVo = this.pmsClient.querySkuById(skuId);
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                throw new RuntimeException("您访问的商品不存在");
            }
            itemVo.setSkuId(skuEntity.getId());
            itemVo.setTitle(skuEntity.getTitle());
            itemVo.setSubtitle(skuEntity.getSubtitle());
            itemVo.setDefaultImage(skuEntity.getDefaultImage());
            itemVo.setPrice(skuEntity.getPrice());
            itemVo.setWeight(skuEntity.getWeight());
            return skuEntity;
        }, executorService);

        //2.根据三级分类id查询一二三级 分类 V
        CompletableFuture<Void> categoryFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<CategoryEntity>> categories = this.pmsClient.queryLvl123CategoriesByCid3(skuEntity.getCategoryId());
            List<CategoryEntity> categoryEntities = categories.getData();
            if (!CollectionUtils.isEmpty(categoryEntities)) {
                itemVo.setCategories(categoryEntities);
            }
        }, executorService);
        //3.根据品牌id查询品牌  V
        CompletableFuture<Void> brandFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<BrandEntity> brandEntityResponseVo = this.pmsClient.queryBrandById(skuEntity.getBrandId());
            BrandEntity brandEntity = brandEntityResponseVo.getData();
            if (brandEntity != null) {
                itemVo.setBrandId(brandEntity.getId());
                itemVo.setBrandName(brandEntity.getName());
            }
        }, executorService);
        //4.根据spuId查询spu  V
        CompletableFuture<Void> spuFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<SpuEntity> spuEntityResponseVo = this.pmsClient.querySpuById(skuEntity.getSpuId());
            SpuEntity spuEntity = spuEntityResponseVo.getData();
            if (spuEntity != null) {
                itemVo.setSpuId(spuEntity.getId());
                itemVo.setSpuName(spuEntity.getName());
            }
        }, executorService);
        //5.根据skuId查询sku图片列表 V
        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuImagesEntity>> skuImagesEntityResponseVo = this.pmsClient.queryImagesBySkuId(skuId);
            List<SkuImagesEntity> skuImagesEntities = skuImagesEntityResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuImagesEntities)) {
                itemVo.setImages(skuImagesEntities);
            }
        }, executorService);
        //6.根据skuId查询营销信息 V
        CompletableFuture<Void> salesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<ItemSaleVo>> itemSaleVosResponseVo = this.smsClient.querySalesBySkuId(skuId);
            List<ItemSaleVo> itemSaleVos = itemSaleVosResponseVo.getData();
            if (!CollectionUtils.isEmpty(itemSaleVos)) {
                itemVo.setSales(itemSaleVos);
            }
        }, executorService);
        //7.根据skuId查询库存 V
        CompletableFuture<Void> storeFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<WareSkuEntity>> wareSkuEntutyResponseVo = this.wmsClient.querySkuById(skuId);
            List<WareSkuEntity> wareSkuEntities = wareSkuEntutyResponseVo.getData();
            if (!CollectionUtils.isEmpty(wareSkuEntities)) {
                itemVo.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0
                ));
            }
        }, executorService);
        //8.根据spuId查询spu下所有sku对应的销售属性 V
        CompletableFuture<Void> salesAttrFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<SaleAttrValueVo>> saleAttrValueVosResponseVo = this.pmsClient.querySaleAttrValuesBySpuId(skuEntity.getSpuId());
            List<SaleAttrValueVo> saleAttrValueVos = saleAttrValueVosResponseVo.getData();
            if (!CollectionUtils.isEmpty(saleAttrValueVos)) {
                itemVo.setSaleAttrs(saleAttrValueVos);
            }
        }, executorService);
        //9.根据skuId查询当前sku的销售属性 V
        CompletableFuture<Void> skuAttrValueFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuAttrValueEntity>> skuAttrValueEntitesResponseVo = this.pmsClient.querySaleAttrValuesBySkuId(skuId);
            List<SkuAttrValueEntity> skuAttrValueEntities = skuAttrValueEntitesResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuAttrValueEntities)) {
                itemVo.setSaleAttr(skuAttrValueEntities.stream().collect(Collectors.toMap(SkuAttrValueEntity::getAttrId, SkuAttrValueEntity::getAttrValue)));
            }
        }, executorService);
        //10.根据spuId查询spu下所有销售属性组合与skuId的映射关系 V
        CompletableFuture<Void> mappingFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<String> stringResponseVo = this.pmsClient.queryMappingBySpuId(skuEntity.getSpuId());
            String json = stringResponseVo.getData();
            if (!StringUtils.isEmpty(json)) {
                itemVo.setSkuJsons(json);
            }
        }, executorService);
        //11.根据spuId查询海报信息 V
        // 使用 Optional 处理可能的空值
        CompletableFuture<Void> descFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            Optional.ofNullable(this.pmsClient.querySpuDescById(skuEntity.getSpuId()))
                    .map(ResponseVo::getData) // 获取 SpuDescEntity
                    .map(SpuDescEntity::getDecript) // 获取 decript 字段
                    .filter(StringUtils::isNotBlank) // 检查 decript 是否非空
                    .ifPresent(decript -> {
                        // 将 decript 按逗号分隔并设置为 spuImage
                        itemVo.setSpuImage(Arrays.asList(StringUtils.split(decript, ",")));
                    });
        }, executorService);
        //12.查询规格参数分组及分组下规格参数与值 V
        CompletableFuture<Void> groupFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<ItemGroupVo>> itemGroupVosResponseVo = this.pmsClient.queryGroupsWithAttrValuesByCategoryIdAndSpuIdAndSkuId(skuEntity.getCategoryId(), skuEntity.getSpuId(), skuId);
            List<ItemGroupVo> itemGroupVos = itemGroupVosResponseVo.getData();
            if (!CollectionUtils.isEmpty(itemGroupVos)) {
                itemVo.setGroups(itemGroupVos);
            }
        }, executorService);
        CompletableFuture.allOf(categoryFuture, brandFuture, spuFuture, skuImagesFuture, salesFuture, storeFuture,
                salesAttrFuture, skuAttrValueFuture, mappingFuture, descFuture, groupFuture).join();
        // 异步化，不会阻塞动态页面，即使失败也不影响当前动态页面的访问
        this.executorService.execute(()->{
            this.generateHtml(itemVo);
        });
        return itemVo;
    }
}
